// 测试视频下载助手 - 内容脚本

class ContentManager {
  constructor() {
    this.serverUrl = 'http://localhost:8080'
    this.init()
  }

  async init() {
    console.log('测试视频下载助手已加载')
    
    // 加载设置
    await this.loadSettings()
    
    // 监听消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      this.handleMessage(request, sender, sendResponse)
      return true // 保持消息通道开放
    })

    // 注入页面脚本
    this.injectPageScript()
    
    // 添加下载按钮
    this.addDownloadButton()
  }

  // 加载设置
  async loadSettings() {
    try {
      const result = await chrome.storage.sync.get(['serverUrl'])
      if (result.serverUrl) {
        this.serverUrl = result.serverUrl
      }
    } catch (error) {
      console.error('加载设置失败:', error)
    }
  }

  // 处理消息
  async handleMessage(request, sender, sendResponse) {
    try {
      switch (request.action) {
        case 'downloadVideo':
          await this.downloadCurrentVideo()
          sendResponse({ success: true })
          break
        
        case 'batchDownload':
          await this.batchDownload()
          sendResponse({ success: true })
          break
        
        default:
          sendResponse({ success: false, error: '未知操作' })
      }
    } catch (error) {
      console.error('处理消息失败:', error)
      sendResponse({ success: false, error: error.message })
    }
  }

  // 注入页面脚本
  injectPageScript() {
    const script = document.createElement('script')
    script.src = chrome.runtime.getURL('src/inject.js')
    script.onload = function() {
      this.remove()
    }
    ;(document.head || document.documentElement).appendChild(script)
  }

  // 添加下载按钮
  addDownloadButton() {
    // 查找视频容器
    const videoContainer = document.querySelector('.video-container, .player-container, #player')
    
    if (!videoContainer) {
      console.log('未找到视频容器')
      return
    }

    // 创建下载按钮
    const downloadBtn = document.createElement('button')
    downloadBtn.innerHTML = '⬇️ 下载视频'
    downloadBtn.className = 'test-download-btn'
    downloadBtn.style.cssText = `
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 9999;
      padding: 8px 16px;
      background: #1890ff;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      font-weight: 500;
      box-shadow: 0 2px 8px rgba(0,0,0,0.15);
      transition: all 0.2s;
    `

    // 添加悬停效果
    downloadBtn.addEventListener('mouseenter', () => {
      downloadBtn.style.background = '#40a9ff'
      downloadBtn.style.transform = 'translateY(-1px)'
    })

    downloadBtn.addEventListener('mouseleave', () => {
      downloadBtn.style.background = '#1890ff'
      downloadBtn.style.transform = 'translateY(0)'
    })

    // 绑定点击事件
    downloadBtn.addEventListener('click', () => {
      this.downloadCurrentVideo()
    })

    // 添加到页面
    videoContainer.style.position = 'relative'
    videoContainer.appendChild(downloadBtn)
  }

  // 下载当前视频
  async downloadCurrentVideo() {
    try {
      // 获取视频信息
      const videoInfo = this.extractVideoInfo()
      
      if (!videoInfo.url) {
        throw new Error('无法获取视频URL')
      }

      // 获取用户认证信息
      const authInfo = await this.getAuthInfo()

      // 发送下载请求
      const response = await fetch(`${this.serverUrl}/api/download/create`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': authInfo.token ? `Bearer ${authInfo.token}` : ''
        },
        body: JSON.stringify({
          videoUrl: videoInfo.url,
          videoTitle: videoInfo.title,
          courseId: videoInfo.courseId,
          sectionId: videoInfo.sectionId,
          cookies: authInfo.cookies
        })
      })

      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`)
      }

      const result = await response.json()
      
      if (result.success) {
        this.showMessage('下载任务已创建', 'success')
      } else {
        throw new Error(result.message || '创建下载任务失败')
      }

    } catch (error) {
      console.error('下载失败:', error)
      this.showMessage('下载失败: ' + error.message, 'error')
    }
  }

  // 批量下载
  async batchDownload() {
    try {
      // 获取课程所有视频列表
      const videoList = this.extractVideoList()
      
      if (!videoList || videoList.length === 0) {
        throw new Error('未找到可下载的视频')
      }

      // 获取用户认证信息
      const authInfo = await this.getAuthInfo()

      // 发送批量下载请求
      const response = await fetch(`${this.serverUrl}/api/download/batch`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': authInfo.token ? `Bearer ${authInfo.token}` : ''
        },
        body: JSON.stringify({
          videos: videoList,
          cookies: authInfo.cookies
        })
      })

      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`)
      }

      const result = await response.json()
      
      if (result.success) {
        this.showMessage(`已创建 ${videoList.length} 个下载任务`, 'success')
      } else {
        throw new Error(result.message || '创建批量下载任务失败')
      }

    } catch (error) {
      console.error('批量下载失败:', error)
      this.showMessage('批量下载失败: ' + error.message, 'error')
    }
  }

  // 提取视频信息
  extractVideoInfo() {
    const url = window.location.href
    const urlParams = new URLSearchParams(window.location.search)
    
    return {
      url: url,
      title: document.querySelector('h1, .video-title, .title')?.textContent?.trim() || '未知标题',
      courseId: urlParams.get('courseNo') || '',
      sectionId: urlParams.get('sectionNo') || '',
      courseVersionId: urlParams.get('courseVersionId') || ''
    }
  }

  // 提取视频列表
  extractVideoList() {
    const videoLinks = document.querySelectorAll('a[href*="sectionNo"]')
    const videos = []

    videoLinks.forEach(link => {
      const href = link.href
      const title = link.textContent?.trim() || '未知标题'
      const urlParams = new URLSearchParams(new URL(href).search)
      
      videos.push({
        url: href,
        title: title,
        courseId: urlParams.get('courseNo') || '',
        sectionId: urlParams.get('sectionNo') || '',
        courseVersionId: urlParams.get('courseVersionId') || ''
      })
    })

    return videos
  }

  // 获取认证信息
  async getAuthInfo() {
    try {
      // 获取页面cookies
      const cookies = document.cookie
      
      // 尝试从localStorage获取token
      const token = localStorage.getItem('token') || sessionStorage.getItem('token')
      
      return {
        cookies: cookies,
        token: token
      }
    } catch (error) {
      console.error('获取认证信息失败:', error)
      return {
        cookies: '',
        token: ''
      }
    }
  }

  // 显示消息
  showMessage(message, type = 'info') {
    // 移除已存在的消息
    const existingMessage = document.querySelector('.test-download-message')
    if (existingMessage) {
      existingMessage.remove()
    }

    // 创建消息提示
    const messageDiv = document.createElement('div')
    messageDiv.className = 'test-download-message'
    messageDiv.textContent = message
    messageDiv.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 12px 16px;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 500;
      z-index: 99999;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      ${type === 'success' ? 'background: #f6ffed; color: #52c41a; border: 1px solid #b7eb8f;' : ''}
      ${type === 'error' ? 'background: #fff2f0; color: #ff4d4f; border: 1px solid #ffccc7;' : ''}
      ${type === 'info' ? 'background: #e6f7ff; color: #1890ff; border: 1px solid #91d5ff;' : ''}
    `
    
    document.body.appendChild(messageDiv)
    
    // 3秒后自动移除
    setTimeout(() => {
      if (messageDiv.parentNode) {
        messageDiv.parentNode.removeChild(messageDiv)
      }
    }, 3000)
  }
}

// 初始化
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    new ContentManager()
  })
} else {
  new ContentManager()
}